//冰狐 vue-icefox  @author 磐石 @version 0.0.2
var iceFox ={
    install:function (Vue, options) {
        this.loadMinxin(Vue)
        this.loadComponent(Vue)
		this.loadFilter(Vue)
		this.loadCommenFn(Vue)
		//普通请求
	    Vue.prototype.$http = function(){
			request.apply(this,arguments)
		};
		//上传文件
		Vue.prototype.$upFile = function(){
			upFile.apply(this,arguments);
		}
    },
    //加载Minxin
    loadMinxin:function(Vue){
        var myMinxin = {
            mounted:function(){
                var root = document.querySelector('#root');
                if (root) {
                    root.classList.remove('elehide');
                    root.classList.add('eleshow');
				}
				var _this = this;
				// api.addEventListener({
				// 	name:'viewappear'
				// }, function(ret, err){
				// 	_this.pageOnShow && typeof _this.pageOnShow  == 'function' ? _this.pageOnShow.apply(this) : "";
				// });
				
			},
			methods:this.initBaseMethods(),
        }
        Vue.mixin(myMinxin)
	},
	//初始化公用Vue方法
	initBaseMethods:function(){
		return{
			toSearch:function(){
				fox.navigateTo({
					url:"../shop/search",
				})
			},
			toXieyi:function(){
				fox.navigateTo({
					url:"../login/xieyi?id=6"
				})
			},
			toYinsi:function(){
				fox.navigateTo({
					url:"../login/xieyi?id=3"
				})
			},
			toUrl:function(url){
				if(!url)return 
				fox.navigateTo({url:url})
			},
		}
	},
	//加载filter
	loadFilter:function(Vue){
		//保留2小数位
	    Vue.filter("toFixed", function (num) {  
		   num += '';
		   num = num.replace(/[^0-9|\.]/g, '');
		   if(/^0+/){num = num.replace(/^0+/, '')}
		   if(!/\./.test(num)){num += '.00'}
		   if(/^\./.test(num)){num = '0' + num}
		   num += '00';
		   num = num.match(/\d+\.\d{2}/)[0];
		   return num
	    });
    },
    //加载组件
    loadComponent:function(Vue){
        
	},
	//加载公共函数
	loadCommenFn:function(Vue){
		/**
		 * 表单验证函数
		 * 验证规则  [ {key:"",//验证字段 vue中data 中的值，reqTxt:""//验空时的提示语}]
		*/
		Vue.prototype.$validate = function(options,callBack){
            var _this = this;
            if(!options)return
            for (var i = 0; i < options.length; i++) {
				var element = options[i];
				var targetValue = eval('this.'+element.key);
                if(targetValue == '' || targetValue == undefined || targetValue == null || !Boolean(targetValue)){
                    fox.showToast({title:element.reqTxt})
                    break
                }else{
                    i == options.length - 1 ? callBack.apply(this) :  "";
                    continue;
                }
            }
        }
	}
}
// fox 对象 提供Loading  路由 设置标题  Toast提示 等功能  (依赖APICloud模块 UILoading dialogbox loading图片   可将以下配置项粘贴至config.xml 来快速使用 )
/**
 * <feature name="UILoading" forceBind="true"></feature>
   <feature name="dialogBox" forceBind="true"></feature>
*/
var fox = {
	// 开启loading
	showLoading:function(){
		var UILoading = api.require('UILoading');
		UILoading.keyFrame({
		    rect: {
		        w: 120,
		        h: 120
		    },
		    styles: {
		        bg: 'rgba(0,0,0,0)',   
		        corner: 5,  
		        interval: 150,      
		        frame: {
		            w: 120,
		            h: 120 
		        }
		    },
		    mask:"rgba(255,255,255,0)",
		    content:[{ 
		     "frame":"widget://res/loading/1.png"
		    },{
		     "frame":"widget://res/loading/2.png"
		    },{
		     "frame":"widget://res/loading/3.png" 
		    },{
		     "frame":"widget://res/loading/4.png" 
		    },{
		     "frame":"widget://res/loading/5.png" 
		    },{
		     "frame":"widget://res/loading/6.png" 
		    },{ 
		     "frame":"widget://res/loading/7.png" 
		    },{
		     "frame":"widget://res/loading/8.png" 
		    },{
		     "frame":"widget://res/loading/9.png" 
		    },{
		     "frame":"widget://res/loading/10.png" 
		    },{
		     "frame":"widget://res/loading/11.png" 
		    },{
		     "frame":"widget://res/loading/12.png" 
		    }],
		}); 
	},
	//隐藏loading
	hideLoading:function(){
		var UILoading = api.require('UILoading');
		UILoading.closeKeyFrame();
	},
	/**
	 * 设置标题
	*/
	setNavigationBarTitle:function(params){
		if("title" in params){
			var title = params.title;
			var hd = document.querySelector('.header');
			var titleDomString = hd.querySelector('.middle').querySelector('span');
			titleDomString.innerHTML = title;
		}
	},
	showToast:function(params){
        if("title" in params){
			api.toast({msg:params.title,location:params.location || "bottom",global:true})
		}
	},
	/**
	 *  路由跳转
	*/
	navigateTo:function(params){
		if('url' in params){
			var query = getBannerQuery(params.url);
			api.openWin({
				name:query.url + ".html",
				url:query.url + ".html",
				pageParam:query.params,
				reload:true,
			})
		}
	},
	/**
	 * 路由回退
	*/
	navigateBack:function(params){
		if(params && 'delta' in params){
			hisToWin(params.delta)
		}else{
			api.closeWin();
		}
	},
	/**
	 * 跳转tab层
	*/
	switchTab:function(params){
		if('url' in params){
			api.sendEvent({name:"apiRouterToTab",extra:{idx:params.url}})
			api.closeToWin({
				name:"root"
			});
		}
	},
	/**重定向路由*/
	redirectTo:function(params){
		if('url' in params){
			api.addEventListener({
				name:'viewdisappear'
			},function(){
				api.closeWin();
			});
			var query = getBannerQuery(params.url);
			api.openWin({
				name:query.url + ".html",
				url:query.url + ".html",
				pageParam:query.params,
				reload:true,
			})
		}
	},
	/**
	 * 模态框
	 * @param {String} title 标题
	 * @param {String} content 内容
	 * @param {String} leftBtn 左按钮文案 
	 * @param {String} rightBtn 左按钮文案 
	 * @desc  依赖dialogbox模块   小程序端请勿使用取消按钮实现分之逻辑
	*/
	showModal:function(params){
		var dialogBox = api.require('dialogBox');
		params.title = params.title || '提示';
		params.leftBtn = params.leftBtn || '取消';
		params.rightBtn = params.rightBtn || '确定';
		params.icon = params.icon || 'widget://res/default_icon.png';
		dialogBox.alert({
			texts: {
				title: params.title,
				content: params.content,
				leftBtnTitle: params.leftBtn,
				rightBtnTitle: params.rightBtn
			},
			styles: {
				bg: '#fff',
				w: 300,
				corner:10,
				title: {
					marginT: 20,
					// icon: 'widget://res/lgout.png',
					icon:params.icon || "",
					iconSize: 32,
					titleSize: 18,
					titleColor: '#222'
				},
				content: {
					color: '#666',
					size: 14
				},
				left: {
					marginB:16,
					marginL: 20,
					w: 120,
					h: 35,
					corner: 6,
					bg: '#e5e5e5',
					color: '#fff',
					size: 14
				},
				right: {
					marginB:16,
					marginL: 20,
					w: 120,
					h: 35,
					corner: 6,
					bg: '#FF6189',
					color: '#fff',
					size: 14
				}
			}
		}, function(ret,err) {
			dialogBox.close({
				dialogName: 'alert'
			});
			params.success ? 
			    params.success({confirm:ret.eventType == 'right',cancle:ret.eventType == 'left'}) :
			      ""
			
		});
	},
	//微信分享框
	share:function(callback){
		var dialogBox = api.require('dialogBox');
		dialogBox.actionMenu ({
			rect:{
				h: 150
			},
			items:[
			{
				text: '微信好友',
				icon: 'widget://image/weixin1.png'
			},
			{
				text: '朋友圈',
				icon: 'widget://image/weixin2.png'
			},
			],
			styles:{
				bg:'#FFF',
				column: 2,
				itemText: {
					color: '#000',
					size: 12,
					marginT:8
				},
				itemIcon:{
					size:60
				},
			},
			tapClose:true,
			animation:true,
		}, function(ret){
			dialogBox.close({
				dialogName: 'actionMenu'
			});
			if(ret.eventType == 'click'){
                callback(ret.index)
			}
		});
	},
	//监听改写
	eventCenter:{
		on:function(name,callback){api.addEventListener({name:name},function(ret){if(ret)callback(ret.value)});},
		trigger:function(name,arg){api.sendEvent({name:name,extra:arg})},
	},
	//文件存储（长保存，对于Object类型会自动转换为JSON字符串----会一直存在于手机）
	storage:{
		get:function(key){var userName = api.getPrefs({sync: true,key: key,});return userName},
		set:function(key,value){api.setPrefs({key:key,value:value})},
		remove:function(key){api.removePrefs({key: key})},
	}
}
//请求
function request(apis,params,callback,isLoading,methods){
	if(!apis)return
	console.log(apis+"参数：-----"+JSON.stringify(params))
	isLoading ? "" : fox.showLoading();
	var userToken = fox.storage.get('userToken');
	var _this = this;
	//处理GET和POST 封装请求体
	var reqData = {};
	if(!methods || methods == 'POST'){
		reqData = {
			body:JSON.stringify(params),
		}
	}else if(methods == 'GET'){
		reqData = {
			values:params
		}
	}
	api.ajax({
		url: baseUrl+apis,
		method: methods || 'post',
		data: reqData,
		headers:{
			'Authorization' : userToken,
			'content-type': 'application/json',
		}
	}, function(ret,err) {
		if (err) {
			fox.hideLoading()
			console.log(JSON.stringify(err)+"接口"+apis)
			Vue.prototype.$env = 'dev' ? fox.showToast({title:apis+"~~~错误"}) : fox.showToast({title:"网络开小差了~~"})
		} else {
			isLoading ? "" : fox.hideLoading();
			callback.call(_this,ret);
		}
	});
}
function upFile(src,callback){
	fox.showLoading();
	api.ajax({
		url: baseUrl + '/user/uploadpic',
		method: 'post',
		data: {
			files: {
				'file': src
			}
		}
	}, function(ret, err) {
		fox.hideLoading();
		if (ret.code == 1) {
			callback(ret.data.info)
		} else {
            fox.showToast({title:ret.msg});
		}
	});
}
function formatDate(date) {
	var y = date.getFullYear();
	var m = date.getMonth() + 1;
	m = m < 10 ? '0' + m : m;
	var d = date.getDate();
	d = d < 10 ? ('0' + d) : d;
	return y + '' + m + '' + d;
};
//-----------------------native方法开始-------------------------
//Native 端方法 依赖APICloud及模块
/** 以下是所有需要的模块集合
 * <feature name="clipBoard" forceBind="true"></feature>
*/
/**
 * @desc 返回页面
 * @param 回退个数  => 1 返回上一层页面
 * @dependent NULL
*/
function hisToWin(num){
    if(!num){
		return false
	}
	var wins = api.windows();
	api.closeToWin({
		name:wins[wins.length- 1 - num].name,
	})
}
/**
 * @desc 文本复制功能
 * @param text 为需要复制的文本
 * @dependent  <feature name="clipBoard" forceBind="true"></feature>
*/
function copy(text){
    var clipBoard = api.require('clipBoard');
	clipBoard.set({
   		value: text
	}, function(ret, err) {
    	if (ret) {
        	api.toast({msg:"复制成功",location:"middle"})
		} else {
    		api.toast({msg:"复制失败，请稍后重试",location:"middle"})
    	}
	});
}
/**
 * @desc 保存图片到本地
 * @param url 保存的URL
 * @dependent  NULL
*/
function savePicture(url){
	var timestamp = new Date().getTime()
	api.download({
		url: url,
		savePath: 'fs://test'+timestamp+'.jpeg',
		report: true,
		cache: true,
		allowResume: true
	}, function(ret, err) {
		if(ret){
			api.toast({
				msg:'图片已保存到本地'
			})
		}
		api.saveMediaToAlbum({
			path: 'fs://test'+timestamp+'.jpeg'
		}, function(ret, err) {

		});
	});
}
/**
 * @desc 图片预览功能
 * @param pic 图片数组
 * @param idx 开始预览的下标 默认 0
 * @depenDent <feature name="UIPhotoViewer" forceBind="true"></feature>
*/
function preViewPic(picArr,idx){
    var UIPhotoViewer = api.require('UIPhotoViewer');
	UIPhotoViewer.open({
		images: picArr,
		placeholderImg: 'widget://res/img/apicloud.png',
		bgColor: '#000'
	}, function(ret, err) {
		if(ret.eventType == 'click'){
			UIPhotoViewer.close();
		}
		if(ret.eventType == 'show'){
			idx ? UIPhotoViewer.setIndex({
				index: idx 
			})  : ""
		}
	});
}
//-----------------------native方法结束-------------------------
//-----------------------DOM系统方法开始-------------------------
//DOM系统方法
/**
 * @desc 长按方法
 * @param id 元素ID
 * @param func 长按事件回调
*/
function longpress(id, func) {
	var timeOutEvent;
	document.querySelector('#' + id).addEventListener('touchstart', function (e) {
		// 开启定时器前先清除定时器，防止重复触发
		clearTimeout(timeOutEvent);
		// 开启延时定时器
		timeOutEvent = setTimeout(function () {
			// 调用长按之后的逻辑函数func
			func(e);
		}, 400);  // 长按时间为300ms，可以自己设置
	});
	document.querySelector('#' + id).addEventListener('touchmove', function (e) {
		// 长按过程中，手指是不能移动的，若移动则清除定时器，中断长按逻辑
		clearTimeout(timeOutEvent);
		/* e.preventDefault() --> 若阻止默认事件，则在长按元素上滑动时，页面是不滚动的，按需求设置吧 */
	});
	document.querySelector('#' + id).addEventListener('touchend', function (e) {
		// 若手指离开屏幕时，时间小于我们设置的长按时间，则为点击事件，清除定时器，结束长按逻辑
		clearTimeout(timeOutEvent);
	});
}
/**
 * @desc 获取元素的css值 
 * @param：元素选择器。
 * @param：某个css的字符串。
 * @param: 切除最后两位个数 50px => 50  
*/
function getEleCss(ele,cssMsg,iscut){
	var eleStyle,num;
	if (window.getComputedStyle) {
		eleStyle = window.getComputedStyle(ele,null);
		num = iscut ? eleStyle[cssMsg].substring(0,eleStyle[cssMsg].length-iscut) : eleStyle[cssMsg];
	} else {
		console.err('your brower is not support')
		num = "";
	}
	return num
}
/**
 * @desc 动态加载JS
 * @param url  加载JS的路径
 * @param callback  加完JS后的回调函数
*/
function loadJs(url, callback) {
	var script = document.createElement('script');
	script.type = "text/javascript";
	if (typeof (callback) != "undefined") {
		if (script.readyState) {
			script.onreadystatechange = function () {
				if (script.readyState == "loaded" || script.readyState == "complete") {
					script.onreadystatechange = null;
					callback();
				}
			}
		} else {
			script.onload = function () {
				callback();
			}
		}
	}
	script.src = url;
	document.body.appendChild(script);
}
// 保存图片到本地
function savePicture(url){
	var timestamp = new Date().getTime()
	api.download({
		url: url,
		savePath: 'fs://test'+timestamp+'.jpeg',
		report: true,
		cache: true,
		allowResume: true
	}, function(ret, err) {
		if(ret){
			api.toast({
				msg:'图片已保存到本地'
			})
		}
		api.saveMediaToAlbum({
			path: 'fs://test'+timestamp+'.jpeg'
		}, function(ret, err) {

		});
	});
}
//-----------------------DOM系统方法结束-------------------------
//-----------------------杂项方法开始-------------------------
//杂项方法
/**
 * @desc 计算缓存
 * @param ：字节数
*/
function formatSize(size){
	if (typeof +size !== 'number') {
        throw new Error('Argument(s) is illegal !')
	}
    const unitsHash = 'B,KB,MB,GB'.split(',')
    let index = 0
    while (size > 1024 && index < unitsHash.length) {
        size /= 1024
        index++
    }
    return Math.round(size * 100) / 100 + unitsHash[index]
}
/**
 * url参数解析
 * @param url = > http://www.baidu.com?id=2
 * @result {url:"http:.//www.baidu.com",params:{id:2}}
 * */
function getBannerQuery(url) {
	if (!url) {
	return false
	}
	var obj = {};
	var urlArr = url.split('?');
	obj.url = urlArr[0];
	if (urlArr.length == 2) {
		var param = urlArr[1].split('&');
		var xinObj = {};
		for (var i = 0; i < param.length; i++) {
			var eleArr = param[i].split('=');
			xinObj[eleArr[0]] = eleArr[1];
		};
		obj.params = xinObj;
	}
	return obj;
}
//-----------------------杂项方法结束-------------------------